package com.yibo.manager.user.service.manager;

import com.yibo.db.user.entity.ManagerUser;
import com.yibo.db.user.mapper.manageruser.ManagerUserMapper;
import com.yibo.manager.user.pojo.ManagerUserMsg;
import com.yibo.support.encry.MD5Helper;
import com.yibo.support.helper.Assert;
import com.yibo.support.helper.ObjectHelper;
import com.yibo.support.helper.TimeHelper;
import com.yibo.support.inter.Command;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.yibo.support.constant.MsgConstant.USER_OR_PSWD_ERROR;

public class LoginManagerCommand implements Command<ManagerUserMsg> {

    private String userId;

    private String password;

    private String ip;

    private ManagerUserMsg result = new ManagerUserMsg();

    public LoginManagerCommand(String userId,String password){
        this.userId = userId;
        this.password = password;
    }

    @Override
    public ManagerUserMsg execute() {
        initIp();

        ManagerUser user = getBean(ManagerUserMapper.class).selectById(this.userId);
        Assert.notEmpty(USER_OR_PSWD_ERROR,user);

        String pwd= user.getPassword();
        Assert.isTrue(USER_OR_PSWD_ERROR,!pwd.equals(MD5Helper.getMD5String(this.password)));

        String sessionId = ObjectHelper.primaryKey();
        result.setLastLoginTime(TimeHelper.getNow())
                .setSessionId(sessionId)
                .setManagerUser(user);

        System.setProperty(sessionId,user.getUserId());
        return result;
    }

    private void initIp(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        this.ip =  request.getRemoteHost();
        result.setIp(ip);
    }
}
